package xyz.yuanjilu.service.impl;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.lionsoul.jcseg.tokenizer.core.ADictionary;
import org.lionsoul.jcseg.tokenizer.core.DictionaryFactory;
import org.lionsoul.jcseg.tokenizer.core.ISegment;
import org.lionsoul.jcseg.tokenizer.core.IWord;
import org.lionsoul.jcseg.tokenizer.core.JcsegTaskConfig;
import org.lionsoul.jcseg.tokenizer.core.SegmentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import xyz.yuanjilu.service.SplitWordService;
/**
 * 需要使用JDK1.8的环境
 * @author qiyang
 */
@Service
public class SplitWordServiceImpl implements SplitWordService{
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    JcsegTaskConfig config = new JcsegTaskConfig(true);
    //创建默认单例词库实现，并且按照config配置加载词库
    ADictionary dic = DictionaryFactory.createSingletonDictionary(config);
    //依据给定的ADictionary和JcsegTaskConfig来创建ISegment
    //为了Api往后兼容，建议使用SegmentFactory来创建ISegment对象
    @Override
    public List<String> getHighWords(String text, int count) {
        List<String> arrayList = new ArrayList<String>();
        try {
            ISegment seg = SegmentFactory.createJcseg(JcsegTaskConfig.COMPLEX_MODE,
                    new Object[] { new StringReader(text), config, dic });
            //备注：以下代码可以反复调用，seg为非线程安全
            seg.reset(new StringReader(text));
            //获取分词结果
            IWord word = null;
            while ((word = seg.next()) != null) {
                //System.out.println(word.getValue());
                arrayList.add(word.getValue());
            } 
        } catch (Exception e) {
            logger.error("分词出现异常", e);
        }
        return arrayList;
    }

    @Override
    public List<String> getHighWords(String text) {
        return this.getHighWords(text, 20);
    }

}
